package com.bwie.gateway.filters;

import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthFilters implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取白名单
        List<String> whites = ignoreWhiteConfig.getWhites();
        //获取
        ServerHttpRequest request1 = exchange.getRequest();
        String path = request1.getURI().getPath();
        if (StringUtils.matches(path, whites)) {
            return chain.filter(exchange);
        }
        //获取token
        String token = request1.getHeaders().getFirst(TokenConstants.TOKEN);
        if (StringUtils.isEmpty(token)) {
            return GatewayUtils.errorResponse(exchange, "token不能为空");
        }
        //token不合法
        String userKey=null;
        try {
            userKey = JwtUtils.getUserKey(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange, "token不合法!");
        }
        if (redisTemplate.hasKey(JwtConstants.USER_KEY+userKey)) {
            return GatewayUtils.errorResponse(exchange, "token过期!");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
